package com.heima.admin.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.heima.admin.feign.ArticleFeign;
import com.heima.admin.feign.WemediaFeign;
import com.heima.admin.mapper.AdChannelMapper;
import com.heima.admin.mapper.AdSensitiveMapper;
import com.heima.admin.service.WemediaNewsAutoScanService;
import com.heima.common.aliyun.GreeTextScan;
import com.heima.common.aliyun.GreenImageScan;
import com.heima.common.fastdfs.FastDFSClient;
import com.heima.model.admin.pojos.AdChannel;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.media.dtos.NewAuthDto;
import com.heima.model.media.pojos.WmNews;
import com.heima.model.media.pojos.WmNewsVo;
import com.heima.model.media.pojos.WmUser;
import com.heima.utils.common.SensitiveWordUtil;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @Title: TODO
 * @Description: TODO
 * @author: 丁丁
 * @date: 2021/3/20
 * @version:
 */
@Service
@Log4j2
//@Transactional
public class WemediaNewsAutoScanServiceImpl implements WemediaNewsAutoScanService {

    @Value("${fdfs.url}")
    private String fileServerUrl;

    @Autowired
    private FastDFSClient fastDFSClient;

    @Autowired
    private WemediaFeign wemediaFeign;

    @Autowired
    private ArticleFeign articleFeign;

    @Autowired
    private AdChannelMapper adChannelMapper;

    @Autowired
    private GreeTextScan greeTextScan;

    @Autowired
    private GreenImageScan greenImageScan;

    @Autowired
    private AdSensitiveMapper adSensitiveMapper;

    /**
     * 自媒体文章审核
     *
     * @param id
     */
    @Override
    @GlobalTransactional
    public void autoScanByMediaNewsId(Integer id) {
        // 1.检查参数
        if (id == null) {
            log.error("当前的审核id空");
            return;
        }
        // 2.根据id查询文章信息
        WmNews wmNews = wemediaFeign.findById(id);
        if (wmNews == null) {
            log.error("审核的自媒体文章不存在，自媒体的id:{}", id);
            return;
        }
        // 3.文章状态为4（人工审核通过）直接保存数据和创建索引
        if (wmNews.getStatus() == 4) {
            // 保存App文章
            saveAppArticle(wmNews);
            return;
        }
        // 4.文章状态为8  发布时间>当前时间 直接保存数据
        if (wmNews.getStatus() == 8 && wmNews.getPublishTime().getTime() <= System.currentTimeMillis()) {
            saveAppArticle(wmNews);
            return;
        }
        // 5.文章状态为1，待审核
        if (wmNews.getStatus() == 1) {
            // 提取文章中的图片和纯文本
            Map<String, Object> contentAndImagesResult = handleTextAndImages(wmNews);
            // 文本审核
            boolean textScanBoolean = handleTextScan((String) contentAndImagesResult.get("contentText"), wmNews);
            if (!textScanBoolean) {
                return;
            }
            // 图片审核
            boolean imagesScanBoolean = handleImagesScan((List<String>) contentAndImagesResult.get("images"), wmNews);
            if (!imagesScanBoolean) {
                return;
            }
            // 自管理敏感词审核
            boolean sensitiveBoolean = handleSensitive((String) contentAndImagesResult.get("contentText"), wmNews);
            if (!sensitiveBoolean) {
                return;
            }
            // 判断是否发布时间>当前时间
            if (wmNews.getPublishTime().getTime() > System.currentTimeMillis()) {
                updateWmNews(wmNews, (short) 8, "审核通过");
                return;
            }
        }
        // 审核通过，修改自媒体文章状态为9，保存app端相关文章信息
        saveAppArticle(wmNews);
    }

    /**
     * 自管理敏感词审核
     *
     * @param contentText
     * @param wmNews
     * @return
     */
    private boolean handleSensitive(String contentText, WmNews wmNews) {
        boolean flag = true;
        // 获取所有自管理敏感词
        List<String> allSensitive = adSensitiveMapper.findAllSensitive();
        // 初始化工具类词典
        SensitiveWordUtil.initMap(allSensitive);
        // 检查是否包含敏感词
        Map<String, Integer> map = SensitiveWordUtil.matchWords(contentText);
        if (map.size() > 0) {
            log.error("敏感词过滤没有通过，包含了敏感词:{}", map);
            // 文章中包含敏感词，审核不通过
            updateWmNews(wmNews, (short) 2, "文章中包含敏感词");
            flag = false;
        }

        return flag;
    }

    /**
     * 调用第三方阿里云检测图片是否违规
     *
     * @param images
     * @param wmNews
     * @return true 审核通过
     */
    private boolean handleImagesScan(List<String> images, WmNews wmNews) {
        boolean flag = true;
        if (images != null && !images.isEmpty()) {
            try {
                // 存储从fastDFS上下载的图片
                List<byte[]> imageList = new ArrayList<>();
                for (String image : images) {
                    String imageName = image.replace(fileServerUrl, "");
                    // 切分出组名和对应的路径名
                    // group1/M00/00/00/wKjIgl892vuAXr_MAASCMYD0yzc919.jpg
                    int indexOf = imageName.indexOf("/");
                    String groupName = imageName.substring(0, indexOf);
                    String imgPath = imageName.substring(indexOf + 1);
                    // 从FastDFS上下载图片
                    byte[] download = fastDFSClient.download(groupName, imgPath);
                    imageList.add(download);
                }
                // 调用接口，检测图片是否违规
                Map map = greenImageScan.imageScan(imageList);
                if (!"pass".equals(map.get("suggestion"))) {
                    // 审核未通过的情况
                    if ("block".equals(map.get("suggestion"))) {
                        // 自媒体文章中图片存在违规
                        updateWmNews(wmNews, (short) 2, "文章中图片有违规");
                        flag = false;
                    }
                    if ("review".equals(map.get("suggestion"))) {
                        // 自媒体文章中图片存在不确定是否违规的情况，需要交给人工审核
                        updateWmNews(wmNews, (short) 3, "文章图片有不确定元素");
                        flag = false;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                flag = false;
            }
        }
        return flag;
    }

    /**
     * 调用第三方阿里云检测文本是否违规
     *
     * @param contentText
     * @param wmNews
     * @return true 审核通过
     */
    private boolean handleTextScan(String contentText, WmNews wmNews) {
        boolean flag = true;
        if (contentText != null) {
            try {
                Map map = greeTextScan.greeTextScan(contentText);
                // 审核未通过
                if (!"pass".equals(map.get("suggestion"))) {
                    if ("block".equals(map.get("suggestion"))) {
                        updateWmNews(wmNews, (short) 2, "文章中包含敏感词");
                        flag = false;
                    }
                    if ("review".equals(map.get("suggestion"))) {
                        updateWmNews(wmNews, (short) 3, "文章中包含不确定词汇");
                        flag = false;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                flag = false;
            }
        }
        return flag;
    }

    /**
     * 提取文章中的纯文本和图片
     *
     * @param wmNews
     * @return
     */
    private Map<String, Object> handleTextAndImages(WmNews wmNews) {
        Map<String, Object> map = new HashMap<>();
        // 获取内容
        String content = wmNews.getContent();
        // 保存纯文本的容器
        StringBuilder sb = new StringBuilder();
        // 保存图片的容器
        List<String> images = new ArrayList<>();
        // 将content内容解析成一个个Map
        List<Map> contentMap = JSONArray.parseArray(content, Map.class);
        for (Map map1 : contentMap) {
            if ("text".equals(map1.get("type"))) {
                sb.append(map1.get("value"));
            }
            if ("image".equals(map1.get("type"))) {
                images.add((String) map1.get("value"));
            }
        }
        // 提取封面图片
        if (wmNews.getImages() != null && wmNews.getType() != 0) {
            String[] split = wmNews.getImages().split(",");
            images.addAll(Arrays.asList(split));
        }
        sb.append(wmNews.getTitle()).append(wmNews.getLabels());
        // 封装结果
        map.put("contentText", sb.toString());
        map.put("images", images);
        return map;
    }

    /**
     * 保存App文章
     *
     * @param wmNews
     */
    private void saveAppArticle(WmNews wmNews) {
        // 检查参数
        if (wmNews == null) {
            log.error("saveAppArticle----WmNews参数异常");
            return;
        }
        // 保存App文章
        ApArticle apArticle = saveArticle(wmNews);
        // 保存文章配置
        saveArticleConfig(apArticle);
        // 保存文章内容
        saveArticleContent(apArticle, wmNews);
        // 修改文章状态
        updateWmNews(wmNews, (short) 9, "审核通过");
    }

    /**
     * 修改文章状态
     *
     * @param wmNews
     * @param i
     * @param msg
     */
    private void updateWmNews(WmNews wmNews, short i, String msg) {
        wmNews.setStatus(i);
        wmNews.setReason(msg);
        wemediaFeign.updateWmnews(wmNews);
    }

    /**
     * 保存文章内容
     *
     * @param apArticle
     * @param wmNews
     */
    private void saveArticleContent(ApArticle apArticle, WmNews wmNews) {
        ApArticleContent apArticleContent = new ApArticleContent();
        apArticleContent.setArticleId(apArticle.getId());
        apArticleContent.setContent(wmNews.getContent());
        articleFeign.saveArticleContent(apArticleContent);
    }

    /**
     * 保存文章配置
     *
     * @param apArticle
     */
    private void saveArticleConfig(ApArticle apArticle) {
        ApArticleConfig apArticleConfig = new ApArticleConfig();
        apArticleConfig.setArticleId(apArticle.getId());
        apArticleConfig.setIsForward(true);
        apArticleConfig.setIsDelete(false);
        apArticleConfig.setIsDown(true);
        apArticleConfig.setIsComment(true);
        articleFeign.saveArticleConfig(apArticleConfig);
    }

    /**
     * 保存文章基本信息
     *
     * @param wmNews
     * @return
     */
    private ApArticle saveArticle(WmNews wmNews) {
        ApArticle apArticle = new ApArticle();
        apArticle.setTitle(wmNews.getTitle());
        apArticle.setLayout(wmNews.getType());
        apArticle.setImages(wmNews.getImages());
        apArticle.setCreatedTime(new Date());
        apArticle.setPublishTime(wmNews.getPublishTime());
        // 查询作者信息
        Integer wmNewsUserId = wmNews.getUserId();
        WmUser wmUser = wemediaFeign.findWmUserById(wmNewsUserId);
        if (wmUser != null) {
            // 获取是否存在该作者
            String wmUserName = wmUser.getName();
            ApAuthor apAuthor = articleFeign.selectAuthorByName(wmUserName);
            if (apAuthor != null) {
                apArticle.setAuthorId(apAuthor.getId().longValue());
                apArticle.setAuthorName(apAuthor.getName());
            }
        }

        // 查询频道信息
        Integer channelId = wmNews.getChannelId();
        AdChannel channel = adChannelMapper.selectById(channelId);
        if (channel != null) {
            apArticle.setChannelId(channel.getId());
            apArticle.setChannelName(channel.getName());
        }
        return articleFeign.saveArticle(apArticle);
    }

    /**
     * 根据文章标题分页查询自媒体文章列表
     *
     * @param dto
     * @return
     */
    @Override
    public PageResponseResult findNews(NewAuthDto dto) {
        //分页查询
        PageResponseResult responseResult = wemediaFeign.findList(dto);
        //有图片需要显示，需要fasfdfs服务器地址
        responseResult.setHost(fileServerUrl);
        return responseResult;
    }

    /**
     * 根据文章id文章信息
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult findOne(Integer id) {
        if (id==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmNewsVo wmNewsVo = wemediaFeign.findWmNewsVo(id);
        if (wmNewsVo==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        ResponseResult responseResult = ResponseResult.okResult(wmNewsVo);
        responseResult.setHost(fileServerUrl);
        return responseResult;
    }

    /**
     * 审核通过或驳回
     *
     * @param type 0 为驳回  1位通过
     * @param dto
     * @return
     */
    @Override
    public ResponseResult updateStatus(Integer type, NewAuthDto dto) {
        // 检查参数
        if (dto==null||dto.getId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 查询文章数据
        WmNews wmNews = wemediaFeign.findById(dto.getId());
        if (wmNews==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        // 判断审核是否通过
        if (type.equals(0)){
            // 审核不通过
            updateWmNews(wmNews,(short)2, dto.getMsg());
        } else {
            // 审核通过
            updateWmNews(wmNews,(short)4, "人工审核通过");
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
